#pragma once
#include "DXUT.h"
#include <vector>
#include <string>

struct Particle
{
	D3DXVECTOR3 initialPosition;
	D3DXVECTOR3 initialVelocity;
	float initialSize;
	float initialTime;
	float lifeTime;
	float mass;
	D3DCOLOR initialColor;

	static D3DVERTEXELEMENT9 ParticleElements[];
	static IDirect3DVertexDeclaration9 *Decl; 
	static void InitDecl(IDirect3DDevice9 *pd3dDevice);
	static void ReleaseDecl();
};

class PSystem
{
public:
	PSystem(const std::wstring& fxName, const std::string& techName, const std::wstring& texName, 
		const D3DXVECTOR3& accel, const int maxNumParicles, const float timePerParticle)
		: m_fxName(fxName), m_techName(techName), m_texName(texName), m_accel(accel),
		m_maxNumParticles(maxNumParicles), m_timePerParticle(timePerParticle), m_time(0.0f) { }

	virtual ~PSystem(void);

	void Init(IDirect3DDevice9 *pd3dDevice);
	float GetTime() { return m_time; }
	void SetTime(const float time) { m_time = time; }

	void SetWorldMatrix(const D3DXMATRIX& world);
	void AddParticle();

	void OnLostDevice();
	void OnResetDevice(IDirect3DDevice9 *pd3dDevice, int viewportHeight);

	virtual void InitParticle(Particle &p) = 0;
	virtual void Update(float fElapsedTime);
	virtual void Draw(IDirect3DDevice9 *pd3dDevice, 
		const D3DXMATRIX &viewProj, 
		const D3DXVECTOR3 &eyePosW);

	static float GetRandomFloat(float a, float b);
	static void GetRandomVec(D3DXVECTOR3& out);

protected:
	std::wstring m_fxName;
	std::string m_techName;
	std::wstring m_texName;
	//Handles
	D3DXHANDLE m_hTech;
	D3DXHANDLE m_hWVP;
	D3DXHANDLE m_hEyePosL;
	D3DXHANDLE m_hTex;
	D3DXHANDLE m_hTime;
	D3DXHANDLE m_hAccel;
	D3DXHANDLE m_hViewportHeight;

	ID3DXEffect *m_effect;
	IDirect3DTexture9 *m_tex;
	IDirect3DVertexBuffer9 *m_vb;
	D3DXMATRIX m_world;
	D3DXMATRIX m_invWorld;
	float m_time;
	D3DXVECTOR3 m_accel;
	int m_maxNumParticles;
	float m_timePerParticle;
	std::vector<Particle> m_particles;
	std::vector<Particle*> m_aliveParticles;
	std::vector<Particle*> m_deadParticles;
};

